#include "httprequest.h"
#include <QEventLoop>
#include <QTimer>
#include <QHttpMultiPart>
#include <QNetworkReply>
#include <QDateTime>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMutex>

#define UPLOADTIMEOUT 500

HttpRequest::HttpRequest(QObject *parent) : QObject(parent)
{
    uploadTimer = new QTimer;
    uploadTimer->setInterval(UPLOADTIMEOUT);    // 设置超时时间
    uploadTimer->setSingleShot(true);           // 单次触发
    loop = new QEventLoop;
    connect(uploadTimer,
            &QTimer::timeout,
            loop,
            &QEventLoop::quit);
}

HttpRequest *HttpRequest::getObject()
{
    static HttpRequest hr;
    return &hr;
}

bool HttpRequest::uploadHlsUrl(QString httpUrl,QString rtmpUrl, QString hlsUrl, int id)
{
    static QMutex httpMutex;
    QMutexLocker locker(&httpMutex);
    QUrl url(httpUrl);
    QNetworkRequest request;
    request.setUrl(url);
    request.setRawHeader("Content-Type","application/json");
    request.setRawHeader("Accept","application/json");
    QNetworkReply *reply;
    QNetworkAccessManager manager;
    QJsonObject obj;
    obj.insert("hls_url",hlsUrl);
    obj.insert("rtmp_url",rtmpUrl);
    obj.insert("stream_id",id);
    reply = manager.post(request, QJsonDocument(obj).toJson());
    //超时定时器
    uploadTimer->start();
    if(loop->isRunning())
        loop->quit();
    //阻塞等待传输结束
    connect(reply,&QNetworkReply::finished,loop,&QEventLoop::quit);
    loop->exec();
    uploadTimer->stop();
    QByteArray data = reply->readAll();
    disconnect(reply,nullptr,nullptr,nullptr);
    reply->deleteLater();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    obj = doc.object();
    if(reply->error() != QNetworkReply::NoError)
        return false;
    return true;
}

bool HttpRequest::uploadHlsUrl2(QString httpUrl, QString hlsUrl, QString key)
{
    static QMutex httpMutex;
    QMutexLocker locker(&httpMutex);
    QUrl url(httpUrl + QString("?%1=%2").arg(key).arg(hlsUrl));
    QNetworkRequest request;
    request.setUrl(url);
    request.setRawHeader("Content-Type","application/json");
    request.setRawHeader("Accept","application/json");
    QNetworkReply *reply;
    QNetworkAccessManager manager;

    reply = manager.get(request);
    //超时定时器
    uploadTimer->start();
    if(loop->isRunning())
        loop->quit();
    //阻塞等待传输结束
    connect(reply,&QNetworkReply::finished,loop,&QEventLoop::quit);
    loop->exec();
    uploadTimer->stop();
    QByteArray data = reply->readAll();
    disconnect(reply,nullptr,nullptr,nullptr);
    reply->deleteLater();
    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject obj = doc.object();
    if(reply->error() != QNetworkReply::NoError)
        return false;
    return true;
}
